#用户账户相关功能：注册、短信、登录、注销


from django.db.models import Q

from django.http import JsonResponse
from django.shortcuts import render,HttpResponse,redirect
from utils.image_code import check_code
from web import models
from web.forms.account import RegisterModelForm,SendSmsForm,loginSMSForm,loginForm
from django.conf import settings

def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request,'register.html',{'form':form})
    form = RegisterModelForm(data = request.POST)
    if form.is_valid():
        #验证通过，写入数据库(密码是密文)
        form.save()
        return JsonResponse({'status':True,'data':'/login/'})
    return JsonResponse({'status':False,'error':form.errors})
def send_sms(request):
    # mobile_phone = request.GET.get('mobile_phone')
    # tpl = request.GET.get('tpl')
    # sms_template_id = settings.TENCENT_SMS_TEMPLATE[tpl]
    form = SendSmsForm(request,data=request.GET)
    if form.is_valid():
        return JsonResponse({'status':True})
    return JsonResponse({'status': False, 'error': form.errors})

def login_sms(request):
    if request.method == 'GET':
        form = loginSMSForm()
        return render(request,'login_sms.html',{'form':form})
    form = loginSMSForm(data = request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status':True,'data':'/index/'})
    return JsonResponse({'status': False, 'error': form.errors})

def login(request):
    if request.method == 'GET':
        form = loginForm(request)
        return render(request,'login.html',{'form':form})
    form = loginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        # user_object = models.UserInfo.objects.filter(username=username,password=password).first()
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60*60*24*14)
            return redirect('/index/')
        form.add_error('username','用户名或密码错误')
    return render(request,'login.html',{'form':form})



def image_code(request):
    from io import BytesIO
    from utils.image_code import check_code
    image_object,code = check_code()
    request.session['image_code'] = code

    request.session.set_expiry(60)#修改session的过期时间
    stream = BytesIO()

    image_object.save(stream,'png')
    return HttpResponse(stream.getvalue())

def logout(request):
    request.session.flush()
    return redirect('index')















